#include "audioplayer.h"

class AudioPlayerImpl : public AudioPlayer {
public:
	AudioPlayerImpl();
	virtual ~AudioPlayerImpl();
	
	virtual bool init(JNIEnv * env, unsigned int rate, int bits, int channels);
	virtual void destroy(JNIEnv * env);
	virtual void start(JNIEnv * env);
	virtual void stop(JNIEnv * env);
	virtual void pause(JNIEnv * env);
	virtual void play(JNIEnv * env, void *data, int size);
	
	
private:
	
	
	jclass jPeerClass;
	jmethodID _init;
	jmethodID _destroy;
	jmethodID _start;
	jmethodID _stop;
	jmethodID _pause;
	jmethodID _play;
	
	jbyteArray jAudioBuffer;
	
};

AudioPlayerImpl::AudioPlayerImpl()
{
}

AudioPlayerImpl::~AudioPlayerImpl()
{
}

bool AudioPlayerImpl::init(JNIEnv * env, unsigned int rate, int bits, int channels)
{
	
	jPeerClass = env->FindClass("eu/codlab/game/gameba/AudioPlayer");
	jPeerClass = (jclass) env->NewGlobalRef(jPeerClass);
	
	jAudioBuffer = env->NewByteArray(8192);
	jAudioBuffer = (jbyteArray) env->NewGlobalRef(jAudioBuffer);
	
	_init=env->GetStaticMethodID(jPeerClass, "init", "(III)Z"); //(IIII)V
	_start=env->GetStaticMethodID(jPeerClass, "start", "()V");; //()V
	_stop=env->GetStaticMethodID(jPeerClass, "stop", "()V");//()V
	_destroy=env->GetStaticMethodID(jPeerClass, "destroy", "()V");//()V
	_pause=env->GetStaticMethodID(jPeerClass, "pause", "()V");//()V
	_play=env->GetStaticMethodID(jPeerClass, "play", "([BI)V");//([BI)V
	
	
	
	jboolean rv = env->CallStaticBooleanMethod(jPeerClass,_init, rate, bits, channels);
	return (rv != JNI_FALSE);
}



void AudioPlayerImpl::destroy(JNIEnv *env)
{
	env->CallStaticVoidMethod(jPeerClass, _destroy);
}

void AudioPlayerImpl::start(JNIEnv *env)
{
	env->CallStaticVoidMethod(jPeerClass, _start);
}

void AudioPlayerImpl::stop(JNIEnv *env)
{
	env->CallStaticVoidMethod(jPeerClass, _stop);
}

void AudioPlayerImpl::pause(JNIEnv *env)
{
	env->CallStaticVoidMethod(jPeerClass, _pause);
}

void AudioPlayerImpl::play(JNIEnv *env, void *data, int size)
{
	env->SetByteArrayRegion(jAudioBuffer, 0, size, (jbyte *) data);
	env->CallStaticVoidMethod(jPeerClass, _play, jAudioBuffer, size);
	
}

extern "C" __attribute__((visibility("default")))
AudioPlayer *createPlayer()
{
	return new AudioPlayerImpl();
}

